<template>
  <div class="achievement-container">
    <van-notice-bar scrollable>
      *根据学校规定，完成以下信息填写才可以提交申请！
    </van-notice-bar>

    <!-- 个人信息卡片 -->
    <div class="user-card">
      <div class="avatar-container">
        <img :src="userInfo.userInfo.userImage" alt="用户头像" class="user-avatar" />
      </div>
      <div class="user-info">
        <div class="info-item">
          <span class="info-label">姓名：</span>
          <span class="info-value">{{ userInfo.userInfo.userName }}</span>
        </div>
        <div class="info-item">
          <span class="info-label">工号：</span>
          <span class="info-value">{{ userInfo.userInfo.userNumber }}</span>
        </div>
        <div class="info-item">
          <span class="info-label">职务：</span>
          <span class="info-value">
            <template v-if="userInfo.userInfo.userType == 1">领导</template>
            <template v-else-if="userInfo.userInfo.userType == 2">辅导员</template>
            <template v-else-if="userInfo.userInfo.userType == 3">教师</template>
          </span>
        </div>
        <div class="info-item">
          <span class="info-label">部门：</span>
          <span class="info-value">{{ userInfo.userInfo.department }}</span>
        </div>
      </div>
    </div>

    <!-- 会议类型 -->
    <van-field
        v-model="meetingType"
        is-link
        readonly
        required
        label="会议类型"
        placeholder="选择类型"
        @click="showPicker1 = true"
        style="margin-top: 20px"
    />
    <van-popup v-model:show="showPicker1" destroy-on-close round position="bottom">
      <van-picker
          :model-value="pickerValue_meetingType"
          :columns="meetingType_list"
          @cancel="showPicker1 = false"
          @confirm="onConfirm_meetingType"
      />
    </van-popup>
    <!-- 班级选择器 -->
    <van-field
        v-model="selectedClassDisplay"
        is-link
        readonly
        required
        label="班级列表"
        placeholder="选择班级"
        @click="showClassPicker = true"
        style="margin-top: 20px"
    />
    <van-popup v-model:show="showClassPicker" destroy-on-close round position="bottom">
      <van-picker
          :columns="classColumns"
          @cancel="showClassPicker = false"
          @confirm="onConfirmClass"
      />
    </van-popup>

    <div class="add_xq">
      <div class="xzq">
        <div class="xzq_left">
          <van-field
              v-model="date_value"
              is-link
              readonly
              placeholder="选择日期"
              @click="showPicker3 = true; setCurrentDate()"
          />
          <van-popup v-model:show="showPicker3" destroy-on-close round position="bottom">
            <van-date-picker
                v-model="currentDate"
                title="选择日期"
                :min-date="minDate"
                :max-date="maxDate"
                @confirm="onConfirmDate"
                @cancel="showPicker3 = false"
            />
          </van-popup>
        </div>
        <div class="xzq_right">
          <van-field
              v-model="time_value"
              is-link
              readonly
              placeholder="选择时间"
              @click="showPicker4 = true; setCurrentTime()"
          />
          <van-popup v-model:show="showPicker4" destroy-on-close round position="bottom">
            <van-time-picker
                v-model="currentTime"
                title="选择时间"
                :formatter="formatter"
                @confirm="onConfirmTime"
                @cancel="showPicker4 = false"
            />
          </van-popup>
        </div>
      </div>

      <div>
        <!-- 会议内容 -->
        <van-cell-group>
          <van-field
              type="textarea"
              v-model="meetingContent"
              label="会议内容"
              placeholder="请填写本次会议育人会议记录："
              rows="5"
              autosize
              maxlength="1000"
              show-word-limit
              style="margin-top: 20px"
          />
        </van-cell-group>

        <div class="upload-section">
          <div class="upload-title">上传图片</div>
          <van-uploader
              v-model="fileList"
              multiple
              :max-count="5"
              :after-read="afterRead"
              class="uploader"
          >
            <template #preview-cover="{ file }">
              <div class="preview-cover">
                {{ file.name }}
              </div>
            </template>
          </van-uploader>
        </div>
      </div>
    </div>

    <div class="dowm_bt">
      <van-button class="zsbc" @click="xq_zsbc" :loading="saving">暂时保存</van-button>
      <van-button class="ljtj" @click="xq_submit" :loading="submitting">立即提交</van-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import {ref, onMounted, computed} from "vue";
import { useUserStore } from '../../Store/modules/userinfo/UserInfo.ts'
import { jiaoshiyurenStore } from '../../Store/modules/jiaoshiyuren.ts'
import { showFailToast, showSuccessToast, showConfirmDialog } from "vant";
import { addSummaryMentorEducationUsingPost } from '../../../src/Api/daoshiyuren.ts';
import {uploadUsingPost} from '../../../src/Api/wenjianshangchuanmokuai.ts'
import router from "../../Router";
import {listClassesByCounselorUsingGet} from "../../Api/banjimokuai.ts";

const userInfo = useUserStore();
const jsyr = jiaoshiyurenStore();

// 表单数据
const meetingContent = ref("");
const fileList = ref<Array<{file?: File, content?: string, name?: string}>>([]);
const meetingType = ref('');
const Class = ref('');
const pickerValue_meetingType = ref<number[]>([]);
const pickerValue_Class = ref<number[]>([]);
const date_value = ref('');
const time_value = ref('');

// 状态
const submitting = ref(false);
const saving = ref(false);

// 会议类型选项
const meetingType_list = [
  { text: '学业指导', value: 3 },
  { text: '组会', value: 2 },
  { text: '班会', value: 1 },
];

// 日期时间相关
const currentDate = ref(['2025', '04', '05']);
const minDate = new Date(2020, 0, 1);
const maxDate = new Date(2099, 12, 31);
const currentTime = ref(['12', '00']);
const showPicker1 = ref(false);
const showPicker3 = ref(false);
const showPicker4 = ref(false);

async function getClass(){
  try {
    const response = await listClassesByCounselorUsingGet({
      counselorId: userInfo.userInfo.userId
    })
    // console.log(response.data.data)
    classList.value = response.data.data

  }catch (err){
    console.log(err)
  }
}

onMounted(() => {
  getClass();
});

// 加载保存的数据
const loadSavedData = () => {
  const saved = jsyr.tempMeetingRecord;

  if (saved.meetingType) meetingType.value = saved.meetingType;
  if (saved.meetingTypeValue) pickerValue_meetingType.value = [saved.meetingTypeValue];
  if (saved.date) date_value.value = saved.date;
  if (saved.time) time_value.value = saved.time;
  if (saved.content) meetingContent.value = saved.content;

  // 恢复班级选择
  if (saved.selectedClass) {
    selectedClass.value = saved.selectedClass;
  }

  // // 处理保存的文件数据
  // if (saved.files?.length) {
  //   fileList.value = saved.files.map(file => ({
  //     file: new File([], file.name, { type: file.type }),
  //     content: file.url,
  //     name: file.name
  //   }));
  // }
}

// 组件挂载时加载保存的数据
onMounted(() => {
  loadSavedData();
});

// 会议类型选择
const onConfirm_meetingType = ({ selectedValues, selectedOptions }: any) => {
  showPicker1.value = false;
  pickerValue_meetingType.value = selectedValues;
  meetingType.value = selectedOptions[0].text;
};

// 定义班级数据类型
interface ClassInfo {
  classId: number;
  className: string;
  grade: string;
  major: string;
  college: string;
  // 其他字段...
}

// 模拟从API获取的班级数据
const classList = ref<ClassInfo[]>([

]);

// 选择器状态
const showClassPicker = ref(false);
const selectedClass = ref<ClassInfo | null>(null);

// 格式化选择器选项
const classColumns = computed(() => {
  return classList.value.map(cls => ({
    text: `${cls.major} ${cls.className}`,
    value: cls.classId,
    classInfo: cls // 保留完整班级信息
  }));
});

// 显示在输入框中的文本
const selectedClassDisplay = computed(() => {
  if (!selectedClass.value) return '';
  return `${selectedClass.value.className}`;
});

// 确认选择班级
const onConfirmClass = ({ selectedOptions }: any) => {
  showClassPicker.value = false;
  selectedClass.value = selectedOptions[0].classInfo;

  // console.log('已选择班级:', selectedClass.value);
};

// 暴露选中的班级信息供父组件使用
defineExpose({
  getSelectedClass: () => selectedClass.value
});

// 日期时间处理
const setCurrentDate = () => {
  const now = new Date();
  currentDate.value = [
    String(now.getFullYear()),
    String(now.getMonth() + 1).padStart(2, '0'),
    String(now.getDate()).padStart(2, '0')
  ];
};

const setCurrentTime = () => {
  const now = new Date();
  currentTime.value = [
    String(now.getHours()).padStart(2, '0'),
    String(now.getMinutes()).padStart(2, '0')
  ];
};

const onConfirmDate = ({ selectedValues }: any) => {
  showPicker3.value = false;
  date_value.value = `${selectedValues[0]}-${selectedValues[1]}-${selectedValues[2]}`;
};

const onConfirmTime = ({ selectedValues }: any) => {
  showPicker4.value = false;
  time_value.value = `${selectedValues[0]}:${selectedValues[1]}`;
};

const formatter = (type: string, option: any) => {
  if (type === 'hour') option.text += '时';
  if (type === 'minute') option.text += '分';
  return option;
};

// 文件上传处理
const afterRead = (file: any) => {
  // 可以在这里添加文件预处理逻辑
  // console.log('文件已选择:', file);
};

// 保存到Pinia
const saveToPinia = async () => {
  try {
    saving.value = true;

    // // 只保存必要的文件信息
    // const savedFiles = fileList.value.map(file => {
    //   const fileObj = file.file || file;
    //   return {
    //     name: fileObj.name,
    //     size: fileObj.size,
    //     type: fileObj.type,
    //     url: file.content || file.url || ''
    //   };
    // });

    jsyr.tempMeetingRecord = {
      meetingType: meetingType.value || '',
      meetingTypeValue: pickerValue_meetingType.value?.[0] ?? null,
      date: date_value.value || '',
      time: time_value.value || '',
      content: meetingContent.value || '',
      // files: savedFiles,
      // 保存完整班级对象
      selectedClass: selectedClass.value ? { ...selectedClass.value } : null,
      // 同时保留显示文本（可选）
      selectedClassDisplay: selectedClassDisplay.value
    };

    showSuccessToast('记录已暂时保存');
  } catch (error) {
    console.error('保存失败:', error);
    showFailToast('保存失败');
  } finally {
    saving.value = false;
  }
}

// 暂时保存按钮点击事件
const xq_zsbc = async () => {
  if (!meetingType.value && !date_value.value && !time_value.value && !meetingContent.value && fileList.value.length === 0) {
    showFailToast('没有内容需要保存');
    return;
  }

  await saveToPinia();
}

// 上传所有文件
const uploadAllFiles = async () => {
  if (fileList.value.length === 0) return [];

  const uploadPromises = fileList.value.map(async (fileItem) => {
    try {
      const file = fileItem.file || fileItem;
      const response = await uploadUsingPost({}, file);

      if (response.data.code === 0 && response.data.data) {
        return response.data.data;
      }
      throw new Error(response.data.message || '文件上传失败');
    } catch (error) {
      console.error('文件上传失败:', error);
      return null;
    }
  });

  const results = await Promise.all(uploadPromises);
  return results.filter(url => url !== null) as string[];
}

// 提交表单
const xq_submit = async () => {
  try {
    submitting.value = true;

    // 验证必填字段
    if (!meetingType.value) {
      showFailToast('请选择会议类型');
      return;
    }
    if (!date_value.value || !time_value.value) {
      showFailToast('请选择会议日期和时间');
      return;
    }
    if (!meetingContent.value) {
      showFailToast('请填写会议内容');
      return;
    }

    // 确认提交
    await showConfirmDialog({
      title: '确认提交',
      message: '确定要提交会议记录吗？提交后不可修改。'
    });

    // 上传文件
    showSuccessToast('正在上传文件...');
    const fileUrls = await uploadAllFiles();
    // console.log(fileUrls)

    // 准备提交数据
    const submitData = {
      meetingType: pickerValue_meetingType.value[0],
      meetingTime: `${date_value.value}T${time_value.value}:00`,
      meetingContent: meetingContent.value,
      photoPath: fileUrls[0],
      organizerId: userInfo.userInfo.userId,
      classId: selectedClass.value.classId,
      className: selectedClass.value.className

    };
    // console.log(submitData)

    // 提交表单
    showSuccessToast('正在提交会议记录...');
    const response = await addSummaryMentorEducationUsingPost(submitData);

    // console.log(response)

    if (response.data.code === 0) {
      // 清除临时数据
      jsyr.$patch({
        tempMeetingRecord: {
          meetingType: '',
          meetingTypeValue: null,
          date: '',
          time: '',
          content: '',
          selectedClassDisplay:'',
          selectedClass:'',
          files: []
        }
      });

      setTimeout(() => {
        showSuccessToast('提交成功！');
      }, 1000)
      router.push('/cqust/yrcg');
    } else {
      throw new Error(response.data.message || '提交失败');
    }
  } catch (error: any) {
    if (error.message !== 'cancel') {
      console.error('提交失败:', error);
      showFailToast(error.message || '提交过程中出错');
    }
  } finally {
    submitting.value = false;
  }
}
</script>

<style scoped>
.achievement-container {
  height: 100vh;
  overflow-y: auto;
  padding: 10px;
  background-color: #f8f9fa;
}

.user-card {
  display: flex;
  background-color: white;
  border-radius: 12px;
  padding: 16px;
  margin-bottom: 20px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.05);
}

.avatar-container {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  overflow: hidden;
  margin-right: 16px;
  border: 2px solid #f0f0f0;
}

.user-avatar {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.user-info {
  flex: 1;
  margin-left: 20px;
}

.info-item {
  margin-bottom: 8px;
  display: flex;
}

.info-label {
  color: #888;
  width: 60px;
  font-size: 14px;
}

.info-value {
  color: #333;
  font-weight: 500;
  font-size: 14px;
}

.add_xq {
  width: 100%;
  margin: 12px auto;
  border-radius: 15px;
  background-color: #fbfbfc;
}

.dowm_bt {
  width: 90%;
  overflow: hidden;
  margin: 20px auto;
}

.zsbc {
  width: 40%;
  background-color: white;
  border-radius: 20px;
  float: left;
}

.ljtj {
  width: 40%;
  background-color: rebeccapurple;
  border-radius: 20px;
  float: right;
  color: white;
}

.xzq {
  width: 100%;
  overflow: hidden;
}

.xzq_left {
  width: 47%;
  float: left;
}

.xzq_right {
  width: 47%;
  float: right;
}

.upload-section {
  background-color: white;
  border-radius: 12px;
  padding: 16px;
}

.upload-title {
  color: #666;
  font-size: 14px;
  margin-bottom: 12px;
}

.uploader {
  margin-top: 8px;
}

.preview-cover {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  padding: 4px;
  font-size: 12px;
  color: white;
  background-color: rgba(0, 0, 0, 0.5);
}
</style>